/**
 * Licensed under the Apache License Version 2.0.
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package net.interknit.knitter.client.java;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;

public class WireAdapterWriter
{
	private final String endpointClassName;

	public WireAdapterWriter(String endpointClassName)
	{
		this.endpointClassName = endpointClassName;
	}

	public void write(File srcDir, String packageName)
	{
		PrintStream out = null;
		try
		{
			InputStream is = getClass().getResourceAsStream("WireAdapter.template");

			BufferedReader br = new BufferedReader(new InputStreamReader(is));

			File targetSourceDir = JavaSourceWriterUtils.packageSourceDir(srcDir, packageName, endpointClassName);

			targetSourceDir.mkdirs();

			File srcFile = new File(targetSourceDir, "WireAdapter.java");
			out = new PrintStream(srcFile);

			out.println("/* !!! GENERATED SOURCE FILE, DO NOT MODIFY !!! */");

			if(packageName != null && ! "".equals(packageName))
			{
				out.println("package " + packageName + ";");
			}

			for(; ;)
			{
				String line = br.readLine();
				if(line != null) out.println(line);
				else break;
			}
		}
		catch(Exception e)
		{
			throw new RuntimeException(e);
		}
		finally
		{
			if(out != null) out.close();
		}
	}
}
